package com.tanhua.server.serivce;

import com.tanhua.domain.db.AnswerList;
import com.tanhua.domain.db.Answers;
import com.tanhua.domain.mongo.OptionList;
import com.tanhua.domain.mongo.PaperType;
import com.tanhua.domain.mongo.QuestionList;
import com.tanhua.domain.mongo.SoulReport;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.TestSoulApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.enums.CoverEnum;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class TestSoulService {

    @Reference
    private TestSoulApi testSoulApi;
    @Reference
    private UserInfoApi userInfoApi;

    private String report = "Report_";

    /**
     *问卷列表
     */
    public ResponseEntity<Object> getQuestion() {
        List<QuestionPaperVo> questionPaperVoList = new ArrayList<>();
        Long userId = UserHolder.getUserId();
        //查询问卷列表
        List<PaperType> papers = testSoulApi.findPaper();
        for (PaperType paper : papers) {
            QuestionPaperVo questionPaperVo = new QuestionPaperVo();
            //获取问卷的id,并存入问卷id,name,cover,level,star信息
            String paperId = paper.getId();
            questionPaperVo.setId(paperId);
            questionPaperVo.setName(paper.getName());
            questionPaperVo.setCover(paper.getCover());
            questionPaperVo.setLevel(paper.getLevel());
            questionPaperVo.setStar(paper.getStar());

            //查询对应的试卷题目，并找到题目对应的答案并封装
            List<QuestionList> questionList = testSoulApi.findQuestionByPid(paperId);

            List<QuestionListVo> questionListVo = new ArrayList<>();
            for (QuestionList question : questionList) {
                QuestionListVo Vo = new QuestionListVo();
                List<OptionListVo> optionListVos = new ArrayList<>();
                Vo.setId(question.getQid());
                Vo.setPid(paperId);
                Vo.setQuestion(question.getQuestion());
                List<OptionList>options = testSoulApi.findOptionByPidAndQid(paperId,question.getQid());
                for (OptionList option : options) {
                    OptionListVo optionListVo = new OptionListVo();
                    optionListVo.setPid(option.getPid());
                    optionListVo.setQid(option.getQid());
                    optionListVo.setId(option.getOid());
                    optionListVo.setOption(option.getOption());
                    optionListVo.setScore(option.getScore());
                    optionListVos.add(optionListVo);
                }
                Vo.setOptions(optionListVos);
                questionListVo.add(Vo);
            }
            questionPaperVo.setQuestions(questionListVo);
            questionPaperVoList.add(questionPaperVo);

            //检测是否解锁，0为解锁，1为锁住
            int i = 0;
            //试卷默认状态为锁定
            questionPaperVo.setIsLock(1);
            if("初级".equals(paper.getLevel())){
                //灵魂测试默认将初级解锁不然无法解锁后续
                questionPaperVo.setIsLock(0);
                i = 1;
            }else if("中级".equals(paper.getLevel())){
                //根据用户id和问卷id查询结果表 若结果表存在说明已经做过此问卷，并解锁下一等级的问卷
                SoulReport report = testSoulApi.findReportByUserIdAndPid(userId,String.valueOf(1));
                if (report!=null){
                    questionPaperVo.setIsLock(0);
                    i = 2;
                }
            }
            else if("高级".equals(paper.getLevel())){
                SoulReport report = testSoulApi.findReportByUserIdAndPid(userId,String.valueOf(i));
                if (report!=null){
                    questionPaperVo.setIsLock(0);
                    i = 3;
                }
            }
            //查询做过的试卷
            SoulReport report = testSoulApi.findReportByUserIdAndPid(userId,String.valueOf(i));
            if (report != null){
                //如果该试卷做过获取到该试卷的报告id以将改试卷设置为查看报告而非开始测试
                questionPaperVo.setReportId(report.getReportId().toString());
            }
        }
        return ResponseEntity.ok(questionPaperVoList);
    }

    /**
     *  提交答卷
     */
    public ResponseEntity submitPaper(AnswerList answers) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //获取时间答案
        List<Answers> list = answers.getAnswers();
        //从题号获取问卷号
        String[] split = answers.getAnswers().get(0).getQuestionId().split("-");
        String pid = split[0];
        //计算分数
        Integer score = 0;
        for (Answers one : list) {
            String questionId = one.getQuestionId();
            String optionId = one.getOptionId();
            Integer number = testSoulApi.findOptionScore(questionId,optionId);
            score = score + number;
        }
        //通过分数得到类型
        Integer reportType = 0;
        if (score <= 20) {
            reportType = 1;
        } else if (score <= 40) {
            reportType = 2;
        } else if (score <= 55) {
            reportType = 3;
        } else {
            reportType = 4;
        }
        //随机生成报告题号
        String reportId = String.valueOf(RandomUtils.nextInt(0, 100)) + userId;
        SoulReport soulReport = new SoulReport();
        soulReport.setReportId(Integer.valueOf(reportId));
        soulReport.setConclusion(testSoulApi.findConclusionByReportType(reportType));
        soulReport.setCover(testSoulApi.findCoverByReportType(reportType));
        soulReport.setScore(score);
        soulReport.setUserId(String.valueOf(userId));
        soulReport.setReportType(reportType);
        soulReport.setPaperId(pid);
        testSoulApi.saveReport(soulReport);
        return ResponseEntity.ok(reportId);
    }

    /**
     * 查看报告
     */
    public ResponseEntity ViewReport(String reportId) {
        //通过报告id拿到报告
        SoulReport soulReport = testSoulApi.findReportByReportId(reportId);
        ReportVo reportVo = new ReportVo();
        //通过查询的报告类型获取类型
        reportVo.setConclusion(soulReport.getConclusion());
        reportVo.setCover(CoverEnum.getName(soulReport.getReportType()));
        //维度
        DimensionsVo dimensionsVo1 = new DimensionsVo();
        dimensionsVo1.setKey("外向");
        dimensionsVo1.setValue(RandomUtils.nextInt(6,10) + "0%");

        DimensionsVo dimensionsVo2 = new DimensionsVo();
        dimensionsVo2.setKey("判断");
        dimensionsVo2.setValue(RandomUtils.nextInt(6,10) + "0%");

        DimensionsVo dimensionsVo3 = new DimensionsVo();
        dimensionsVo3.setKey("抽象");
        dimensionsVo3.setValue(RandomUtils.nextInt(6,10) + "0%");

        DimensionsVo dimensionsVo4 = new DimensionsVo();
        dimensionsVo4.setKey("理性");
        dimensionsVo4.setValue(RandomUtils.nextInt(6,10) + "0%");

        List<DimensionsVo> dimensionsVos = new ArrayList<>();
        dimensionsVos.add(dimensionsVo1);
        dimensionsVos.add(dimensionsVo2);
        dimensionsVos.add(dimensionsVo3);
        dimensionsVos.add(dimensionsVo4);
        //设置参数
        reportVo.setDimensions(dimensionsVos);
        //相似的人
        String userId = soulReport.getUserId();

        //查出分数值相同的人
        List<SoulReport> reports = testSoulApi.findReportByReportType(soulReport.getReportType());
        List<Long> userIdList = new ArrayList<>();
        int i= 0;
        for (int j = 0; j <10; j++) {
            int num = RandomUtils.nextInt(0, reports.size());
            SoulReport soulReport1 = reports.get(num);
            if (soulReport1.getUserId()!=userId && !userIdList.contains(Long.valueOf(soulReport1.getUserId()))){
                userIdList.add(Long.valueOf(soulReport1.getUserId()));
                i++;
            }
        }
        List<SimilarVo> similarVos = new ArrayList<>();
        for (Long id : userIdList) {
            SimilarVo similarVo = new SimilarVo();
            similarVo.setAvatar(userInfoApi.findById(id).getAvatar());
            similarVo.setId(id.intValue());
            similarVos.add(similarVo);
        }
        reportVo.setSimilarYou(similarVos);

        return ResponseEntity.ok(reportVo);
    }
}
